import styles from './index.module.scss'
import { Toast, NavBar, Form, Input, List, Button, InputRef } from 'antd-mobile'
import { useNavigate, useLocation } from 'react-router-dom'
import { LoginForm } from '@/types/data'
import { loginAsync, getCodeAsync } from '@/store/index'
import { useAppDispatch } from '@/store/index'
import { useEffect, useRef, useState } from 'react'
import { FormInstance } from 'antd-mobile/es/components/form'

export default function Login() {
  const navigate = useNavigate()
  const location = useLocation()
  const dispatch = useAppDispatch()
  // 表单校验规则
  const rules = {
    mobile: [
      {
        required: true,
        message: '手机号不能为空'
      },
      {
        pattern: /^1[3-9]\d{9}$/,
        message: '手机号格式错误'
      }
    ],
    code: [
      {
        required: true,
        message: '验证码不能为空'
      },
      {
        pattern: /^\d{6}$/,
        message: '验证码格式错误'
      }
    ]
  }
  // 登录按钮
  async function onFinish(values: LoginForm) {
    try {
      await dispatch(loginAsync(values))
      Toast.show({
        content: '登录成功',
        icon: 'success'
      })
      const { state } = location
      navigate(state ? state.from : '/layout')
    } catch (error) {
      console.log(error)
    }
  }

  // 表单ref
  const formRef = useRef<FormInstance>(null)
  // 手机号ref
  const mobileRef = useRef<InputRef>(null)
  // 倒计时剩余时间
  const [timeLeft, settimeLeft] = useState(0)
  // 定时器timer
  const timerRef = useRef<null | number>(null)

  // 获取验证码
  function onGetCode() {
    const current = formRef.current!
    const mobile = current.getFieldValue('mobile')
    const errors = current.getFieldError('mobile')
    if (!mobile || errors.length > 0) {
      // 未获取到手机号或手机号校验错误，让手机号自动获取焦点
      mobileRef.current?.focus()
      return
    }
    dispatch(getCodeAsync(mobile))

    settimeLeft(60)
    timerRef.current = window.setInterval(() => {
      settimeLeft((timeLeft) => timeLeft - 1)
    }, 1000)
    console.log('发送请求获取验证码')
  }
  // 倒计时为0时，清楚定时器
  useEffect(() => {
    // 副作用函数
    if (timeLeft === 0) {
      clearInterval(timerRef.current as number)
    }
  }, [timeLeft])
  // 组件销毁时，清理定时器
  useEffect(() => {
    return () => {
      // 返回清理函数
      clearInterval(timerRef.current as number)
    }
  }, []) //依赖数组为空时，副作用函数只在组件初始化和卸载时执行

  return (
    <>
      <div className={styles.root}>
        <NavBar onBack={() => navigate(-1)}></NavBar>
        {/* 表单 */}
        <div className="login-form">
          <h2 className="title">账号登录</h2>
          {/* 失去焦点的时候以及改变的时候触发校验 */}
          <Form
            ref={formRef}
            validateTrigger={['onChange', 'onBlur']}
            onFinish={onFinish}
            initialValues={{
              mobile: '13911111111',
              code: '246810'
            }}
          >
            <Form.Item className="login-item" name="mobile" rules={rules.mobile}>
              {/* 关闭历史记录 */}
              <Input placeholder="请输入手机号" autoComplete="off" ref={mobileRef}></Input>
            </Form.Item>
            <List.Item
              className="login-code-extra"
              extra={
                <span className="code-extra" onClick={timeLeft === 0 ? onGetCode : undefined}>
                  {timeLeft === 0 ? '发送验证码' : `${timeLeft}s后重新获取`}
                </span>
              }
            >
              <Form.Item name="code" rules={rules.code} className="login-item">
                <Input autoComplete="off" placeholder="请输入验证码" />
              </Form.Item>
            </List.Item>
            <Form.Item>
              <Button color="primary" block className="login-submit" type="submit">
                登录
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>
    </>
  )
}
